/**
 * @author:  陆楚良 (Email:lu_chuliang@sina.com|QQ:874449204)
 * @version: 1.0.1
 * @license: http://www.apache.org/licenses/LICENSE-2.0
 */

"use strict";

var child = require('child_process')
  , path  = require('path')
  , fs    = require('fs')
;

const GENERATE_PATH = path.dirname(module.filename) + path.sep + "generate.js";

class Build{
    constructor(mainfile){
        this._watch    = [];
        this.mainfile  = mainfile;
        this.generate();
    }

    watch(file){
        this._watch.push(file);
        fs.watchFile(file, { persistent: true, interval: 1000 }, (stats,o_stats)=>{
            this.generate();
        });
    }

    unwatch(){
        this._watch.forEach((v, k)=>{
            fs.unwatchFile(v);
        });
        this._watch = [];
    }

    generate(){
        child.exec('node "'+GENERATE_PATH+'" "'+this.mainfile+'"', null, (err, stdout, stderr)=>{
            process.stdout.cursorTo(0,0);
            process.stdout.clearScreenDown();
            console.log(stdout);
            if(!stderr){
                this.unwatch();
                stdout = stdout.split(/[\r\n]+/);
                var pre,file;
                for(var i=0;i<stdout.length;i++){
                    pre = stdout[i].trim().split(":", 1);
                    switch (pre[0].toLowerCase()) {
                        case "input":
                        case "include":
                        case "string":
                        case "html":
                            file = stdout[i].trim().substr(pre[0].length+1).trim();
                            this.watch(file);
                            break;
                    }
                }
            }else{
                 console.log(stderr);
            }
        });
    }
}
process.argv[2] && new Build(process.argv[2]);
process.argv.splice(3).forEach((main)=>{
    child.exec('start node "'+module.filename+'" "'+main+'"', null, (err, stdout, stderr)=>{});
});
